package com.zed.app.push;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.zed.app.push.util.HttpClient;
import com.zed.common.util.JsonUtils;

public class FcmPush {
	private static final String API_KEY = SystemConfig.getString("remote.push.gcm.apikey");
	private  static final Logger logger = Logger.getLogger(FcmPush.class.getClass());
	
	/**
	 * 发送push消息
	 * @param token
	 * @param payload
	 * @throws Exception
	 */
	public static Map<String,String> pushMsg(int messageType,Map<String, Object> messageData, String toId, String title,String body,String icon,boolean pushToTopic,boolean pushToManyTopic) throws Exception {
		Map<String, String> headers = new HashMap<>();
		headers.put("Content-Type", "application/json");
		headers.put("Authorization", "key="+API_KEY);
		
		Map<String, Object> data = new HashMap<String,Object>(); 
		
		if(messageData == null){
		    messageData = new HashMap<String,Object>();
		}
		
		messageData.put("type", messageType);
		
		data.put("data", messageData);
		// 如果不是发送给主题或者不是发给多个主题时，是设置to属性
//		if(!pushToTopic || !pushToManyTopic){
//			data.put("to", toId);//给指定用户发送
//		}
		data.put("to", toId);//给指定用户发送
//		if(pushToManyTopic){
//			data.put("condition", messageData.get("condition"));
//		}
	
		
		Map<String, Object> notification = new HashMap<String,Object>(); 
		notification.put("title", title);
		notification.put("body", body);
//		notification.put("click_action","com.dezed.push.backdispath");
		if(StringUtils.isNotBlank(icon)){
			notification.put("icon",icon);
		}
//		notification.put("icon", "myicon");
		
		
		//data.put("notification", notification);
		messageData.putAll(notification);
		
		//删除多余的属性
		messageData.remove("condition");
		messageData.remove("messageIcon");
		
		JSONObject json = JSONObject.parseObject(JsonUtils.getJsonStrByMap(data));
		
		if(logger.isInfoEnabled()){
			logger.info("request data :"+json.toJSONString());
		}
		
		return HttpClient.getInstance().doHttpRequest("https://fcm.googleapis.com/fcm/send", headers, json.toJSONString());
	}
	
	/**
	 * 发送push消息
	 * @param token
	 * @param payload
	 * @throws Exception
	 */
	public static Map<String,String> pushMsg(int messageType,Map<String, Object> messageData, String toId, String title,String body,String icon) throws Exception {
		return pushMsg(messageType,messageData,toId,title,body,icon,false,false);
	}
	
	
	public static void main(String [] args) throws Exception{
		
//		System.out.println(FcmPush.pushMsg(null, "fGIjmCygOO8:APA91bHuLA_yaZAn1v-qTZJCptdkx6NShctLkjbJyXqvPPScye647-6AEeeNlyvR53hkGAQjmuUFj_RS6rchu0Fl6A1wgC72MEGfxirxqJng2VwzbnUDtMLILq5x4xEOQBfZg8QdJwrw", "test","hello word"));
	}
	
	
}
